import sys
import mysql.connector
from mysql.connector import Error
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QPushButton, QLineEdit, QMessageBox, QGroupBox,
    QFormLayout, QDoubleSpinBox, QTextEdit, QDialog, QDialogButtonBox
)
from PyQt5.QtGui import QFont
from Customer.db_connector import DBUtils
from Customer.customer_moneymanage import TransactionManager  # 导入交易管理类


class CustomerLoginWindow(QWidget):
    """客户登录窗口"""
    def __init__(self, customer=None, parent=None):
        print("数据库连接初始化")
        try:
            # 数据库连接配置
            self.connection = mysql.connector.connect(
                host='localhost',
                database='bank system',
                user='root',
                password='1234'
            )

            if self.connection.is_connected():
                # 使用推荐的属性替代弃用的方法
                db_info = self.connection.server_info
                print(f"成功连接到MySQL服务器 (版本 {db_info})")
        except Error as e:
            print(f"数据库连接失败: {e}")
            # 显示错误消息框
            QMessageBox.critical(None, "数据库错误", f"无法连接数据库: {str(e)}")
            raise

    def __init__(self):
        super().__init__()
        self.setWindowTitle("银行卡客户登录")
        self.setFixedSize(400, 250)
        self.transaction_manager = None
        self.setup_ui()

    def setup_ui(self):
        """初始化登录界面"""
        layout = QVBoxLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(30, 30, 30, 30)

        # 登录表单
        form_group = QGroupBox("银行卡登录")
        form_layout = QFormLayout()

        self.card_id_input = QLineEdit()
        self.card_id_input.setPlaceholderText("请输入16位银行卡号")
        self.card_id_input.setMaxLength(16)

        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("请输入6位密码")
        self.password_input.setMaxLength(6)
        self.password_input.setEchoMode(QLineEdit.Password)

        form_layout.addRow("卡号:", self.card_id_input)
        form_layout.addRow("密码:", self.password_input)
        form_group.setLayout(form_layout)

        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.clicked.connect(self.handle_login)

        # 布局
        layout.addWidget(form_group)
        layout.addWidget(login_btn)
        self.setLayout(layout)

    def handle_login(self):
        """处理登录逻辑"""
        card_id = self.card_id_input.text().strip()
        password = self.password_input.text().strip()

        if len(card_id) != 16 or not card_id.isdigit():
            QMessageBox.warning(self, "错误", "卡号必须为16位数字")
            return

        if len(password) != 6 or not password.isdigit():
            QMessageBox.warning(self, "错误", "密码必须为6位数字")
            return

        # 验证银行卡和密码
        db = DBUtils()
        try:
            db.connect()
            query = """
            SELECT cardID, customerID, balance, IsReportLoss 
            FROM cardInfo 
            WHERE cardID = %s AND pass = %s
            """
            result = db.execute_query(query, (card_id, password))

            if not result:
                QMessageBox.warning(self, "登录失败", "卡号或密码错误")
                return

            if result[0]['IsReportLoss'] == '是':
                QMessageBox.warning(self, "登录失败", "该卡已挂失，无法登录")
                return

            # 登录成功，打开客户操作界面
            self.transaction_manager = TransactionManager()
            self.customer_window = CustomerOperationWindow(
                card_id,
                result[0]['customerID'],
                result[0]['balance'],
                self.transaction_manager
            )
            self.customer_window.show()
            self.hide()

        except Exception as e:
            QMessageBox.critical(self, "错误", f"登录时发生错误: {str(e)}")
        finally:
            db.disconnect()


class CustomerOperationWindow(QMainWindow):
    """客户操作主界面"""

    def __init__(self, card_id, customer_id, balance, transaction_manager):
        super().__init__()
        self.card_id = card_id
        self.customer_id = customer_id
        self.balance = balance
        self.transaction_manager = TransactionManager()

        self.setWindowTitle(f"银行卡操作 - 卡号: {card_id}")
        self.setFixedSize(1100, 800)
        self.setup_ui()

    def setup_ui(self):
        """初始化操作界面"""
        central_widget = QWidget()
        layout = QVBoxLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)

        # 账户信息显示
        info_group = QGroupBox("账户信息")
        info_layout = QFormLayout()

        self.balance_label = QLabel(f"¥ {self.balance:.2f}")
        self.balance_label.setStyleSheet("font-size: 18px; font-weight: bold;")

        info_layout.addRow("卡号:", QLabel(self.card_id))
        info_layout.addRow("客户ID:", QLabel(str(self.customer_id)))
        info_layout.addRow("当前余额:", self.balance_label)
        info_group.setLayout(info_layout)

        # 操作按钮
        btn_group = QGroupBox("银行业务")
        btn_layout = QVBoxLayout()

        self.deposit_btn = QPushButton("存款")
        self.withdraw_btn = QPushButton("取款")
        self.logout_btn = QPushButton("退出登录")

        self.deposit_btn.clicked.connect(self.show_deposit_dialog)
        self.withdraw_btn.clicked.connect(self.show_withdraw_dialog)
        self.logout_btn.clicked.connect(self.logout)

        btn_layout.addWidget(self.deposit_btn)
        btn_layout.addWidget(self.withdraw_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.logout_btn)
        btn_group.setLayout(btn_layout)

        # 交易记录显示
        self.transaction_log = QTextEdit()
        self.transaction_log.setReadOnly(True)
        self.load_transaction_history()

        # 布局
        layout.addWidget(info_group)
        layout.addWidget(btn_group)
        layout.addWidget(QLabel("最近交易记录:"))
        layout.addWidget(self.transaction_log)
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def show_deposit_dialog(self):
        """显示存款对话框"""
        dialog = QDialog(self)
        dialog.setWindowTitle("存款")
        dialog.setFixedSize(300, 200)

        layout = QVBoxLayout()

        amount_spin = QDoubleSpinBox()
        amount_spin.setRange(1, 1000000)
        amount_spin.setPrefix("¥ ")
        amount_spin.setDecimals(2)

        remark_input = QLineEdit()
        remark_input.setPlaceholderText("可选备注")

        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)

        form = QFormLayout()
        form.addRow("存款金额:", amount_spin)
        form.addRow("备注:", remark_input)

        layout.addLayout(form)
        layout.addWidget(btn_box)
        dialog.setLayout(layout)

        if dialog.exec_() == QDialog.Accepted:
            amount = amount_spin.value()
            remark = remark_input.text().strip() or None

            if self.transaction_manager.deposit(self.card_id, amount, remark):
                QMessageBox.information(self, "成功", f"成功存入 ¥{amount:.2f}")
                self.update_balance()
                self.load_transaction_history()
            else:
                QMessageBox.warning(self, "失败", "存款操作失败")

    def show_withdraw_dialog(self):
        """显示取款对话框"""
        dialog = QDialog(self)
        dialog.setWindowTitle("取款")
        dialog.setFixedSize(300, 250)

        layout = QVBoxLayout()

        amount_spin = QDoubleSpinBox()
        amount_spin.setRange(1, 1000000)
        amount_spin.setPrefix("¥ ")
        amount_spin.setDecimals(2)

        password_input = QLineEdit()
        password_input.setPlaceholderText("请输入6位密码")
        password_input.setMaxLength(6)
        password_input.setEchoMode(QLineEdit.Password)

        remark_input = QLineEdit()
        remark_input.setPlaceholderText("可选备注")

        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)

        form = QFormLayout()
        form.addRow("取款金额:", amount_spin)
        form.addRow("交易密码:", password_input)
        form.addRow("备注:", remark_input)

        layout.addLayout(form)
        layout.addWidget(btn_box)
        dialog.setLayout(layout)

        if dialog.exec_() == QDialog.Accepted:
            amount = amount_spin.value()
            password = password_input.text().strip()
            remark = remark_input.text().strip() or None

            if self.transaction_manager.withdraw(self.card_id, amount, password, remark):
                QMessageBox.information(self, "成功", f"成功取出 ¥{amount:.2f}")
                self.update_balance()
                self.load_transaction_history()
            else:
                QMessageBox.warning(self, "失败", "取款操作失败")

    def update_balance(self):
        """更新余额显示"""
        db = DBUtils()
        try:
            db.connect()
            query = "SELECT balance FROM cardInfo WHERE cardID = %s"
            result = db.execute_query(query, (self.card_id,))
            if result:
                self.balance = result[0]['balance']
                self.balance_label.setText(f"¥ {self.balance:.2f}")
        except Exception as e:
            print(f"更新余额失败: {e}")
        finally:
            db.disconnect()

    def load_transaction_history(self):
        """加载交易记录"""
        db = DBUtils()
        try:
            db.connect()
            query = """
            SELECT tradeDate, tradeType, tradeMoney, remark 
            FROM tradeInfo 
            WHERE cardID = %s 
            ORDER BY tradeDate DESC 
            LIMIT 10
            """
            transactions = db.execute_query(query, (self.card_id,))

            self.transaction_log.clear()
            if transactions:
                log_text = "日期\t\t类型\t金额\t备注\n"
                log_text += "-" * 50 + "\n"
                for trans in transactions:
                    log_text += (
                        f"{trans['tradeDate'].strftime('%Y-%m-%d %H:%M')}\t"
                        f"{trans['tradeType']}\t"
                        f"¥{trans['tradeMoney']:.2f}\t"
                        f"{trans.get('remark', '')}\n"
                    )
                self.transaction_log.setPlainText(log_text)
            else:
                self.transaction_log.setPlainText("暂无交易记录")

        except Exception as e:
            print(f"加载交易记录失败: {e}")
            self.transaction_log.setPlainText("无法加载交易记录")
        finally:
            db.disconnect()

    def logout(self):
        """退出登录"""
        self.close()
        login_window = CustomerLoginWindow()
        login_window.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 设置全局字体
    font = QFont()
    font.setFamily("Microsoft YaHei" if sys.platform == 'win32' else "Arial")
    font.setPointSize(10)
    app.setFont(font)

    window = CustomerLoginWindow()
    window.show()
    sys.exit(app.exec_())